<template>
  <div>
    <div class="upload-item-left">
      <div
        v-for="(item, index) in state.fileList"
        :key="index"
        class="upload-item-left"
      >
        <div
          v-if="item.type === 'video'"
          style="width: 100%; padding-right: 10px"
        >
          <audio
            :style="{
              width: '250px',
            }"
            controls="controls"
            :src="item.url"
          >
            您的浏览器不支持音频播放
          </audio>
          <!-- <span>{{ item.name }}</span> -->
          <i
            v-if="uploadDisabled"
            class="el-icon-delete-solid del-icon"
            @click="remove(index)"
          ></i>
        </div>
        <div
          v-if="item.type === 'img'"
          style="width: 100%; padding-right: 10px"
        >
          <el-image
            :style="{
              width: state.size + 'px',
              height: state.size + 'px',
              lineHeight: state.size + 'px',
            }"
            :src="item.url"
            :preview-src-list="state.imgFileList"
            :preview-teleported="true"
          >
          </el-image>
          <!-- <span>{{ item.name }}</span> -->
          <i
            v-if="uploadDisabled"
            class="el-icon-delete-solid del-icon"
            @click="remove(index)"
          ></i>
        </div>
        <div
          v-if="item.type === 'other'"
          style="width: 100%; padding-right: 10px"
        >
          <p class="download-a" @click="clickLink($event, item)">
            {{ item.name }}
          </p>
        </div>
      </div>
      <span v-if="!state.fileList.length">-</span>

      <!-- <div
        v-if="!uploadDisabled && !fileData.length"
        class="bgimg"
        :style="{
          width: size + 'px',
          height: size + 'px',
          lineHeight: size + 'px',
        }"
      ></div> -->
    </div>

    <el-upload
      v-if="uploadDisabled"
      :action="action"
      :headers="state.myHeaders"
      multiple
      :limit="limit"
      :on-success="handleVideoSuccess"
      :before-upload="beforeUpload"
      :on-progress="uploadVideoProcess"
      :on-preview="handlePreview"
      :file-list="state.fileList"
    >
      <div
        v-if="state.videoFlag == false"
        :style="{
          width: state.size + 'px',
          height: state.size + 'px',
          lineHeight: state.size + 'px',
        }"
      >
        <i class="el-icon-plus"></i>
      </div>

      <el-progress
        v-if="state.videoFlag == true"
        type="circle"
        :percentage="state.videoUploadPercent"
        style="margin-top: 30px"
      ></el-progress>
    </el-upload>
    <p v-if="uploadDisabled">
      请上传<span>{{ fileType.join('/') }}</span
      >格式文件，且大小不超过<span>{{ fileSize }}</span
      >Mb
    </p>
  </div>
</template>

<script setup name="UploadList">
import axios from 'axios'

import { mapState } from 'vuex'
const { proxy } = getCurrentInstance()
const emit = defineEmits()

const props = defineProps({
  // 上传地址
  action: {
    type: String,
    // required: true,
  },
  //文件大小
  fileSize: {
    type: Number,
    default: 20,
  },
  //回显文件数据
  fileData: {
    type: Array,
    default() {
      return []
    },
  },
  //组件可编辑性
  uploadDisabled: {
    type: Boolean,
    default: true,
  },
  // 支持上传的文件类型
  fileType: {
    type: Array,
    default() {
      return [
        'png',
        'jpg',
        'jpeg',
        'pdf',
        'mp3',
        'm4a',
        'aac',
        'wav',
        'audio',
        'x-m4a',
      ]
    },
  },
  //
  limit: {
    type: Number,
    default: 3,
  },
})
const state = reactive({
  myHeaders: {
    Authorization: '',
  },
  size: 100, //高宽
  videoFlag: false,
  videoUploadPercent: 0, //视频上传进度
  imgFileList: [], //图片文件列表
  fileList: [], //文件列表
  urlList: [], //地址列表
})
const token = computed(() => {
  return proxy.$store.state.user.token
})

watch(
  () => state.fileList,
  (val) => {
    if (val.length) {
      state.imgFileList = []
      val.forEach((item) => {
        if (item.type === 'img') {
          state.imgFileList.push(item.url)
        }
      })
    }
  }
)

watch(
  () => state.urlList,
  () => {
    emit('upload', val)
  }
)

watch(
  () => props.fileData,
  (val) => {
    if (val.length) {
      state.fileList = val.map((item, index) => {
        let imgType = ['png', 'jpg', 'jpeg', 'gif']
        let videoType = ['mp3', 'm4a', 'aac', 'wav', 'audio', 'x-m4a']
        let wordType = ['docx', 'doc', 'pdf', 'xls', 'xlsx']
        let type = item.filePath.split('.')[1]
        let name = item.name
        if (imgType.indexOf(type) > -1) {
          item = {
            type: 'img',
            name: name,
            url: axios.defaults.baseURL + '/pub' + item.filePath,
          }
        } else if (videoType.indexOf(type) > -1) {
          // const xhr = new XMLHttpRequest()
          item = {
            type: 'video',
            name: name,
            url: axios.defaults.baseURL + '/pub' + item.filePath,
          }
        } else if (wordType.indexOf(type) > -1) {
          item = {
            type: 'other',
            name: name,
            url: '/pub' + item.filePath,
          }
        }
        return item
      })
    } else {
      state.fileList = []
    }
  },
  {
    deep: true,
    immediate: true,
  }
)
onMounted(() => {
  state.myHeaders.Authorization = token
})
//clickLink
const clickLink = (e, file) => {
  if (file) {
    axios({ method: 'get', url: file.url, responseType: 'blob' }).then(
      (res) => {
        let blob = res
        let urlL = window.URL.createObjectURL(new Blob([blob]))
        let link = document.createElement('a')
        link.href = urlL
        link.download = file.name
        link.click()
      }
    )
  }
}
//删除
const remove = (index) => {
  state.fileList.splice(index, 1)
  state.urlList.splice(index, 1)
}

const handlePreview = (file) => {}
//验证文件格式和文件大小
const beforeUpload = (file) => {
  //验证文件格式
  let fileTypeArr = file.type.split('/')
  if (props.fileType.indexOf(fileTypeArr[1]) === -1) {
    proxy.$message.error(
      `文件格式不正确, 请上传 ${props.fileType.join(' / ')} 格式文件!`
    )
    return false
  }
  let file_type_list = proxy.$store.state.permission.dict['file_type_list']
  if (file_type_list && file_type_list.length) {
    let uploadType = file.name.split('.')[file.name.split('.').length - 1]
    let file_type_list_arr = []
    file_type_list.forEach((item) => {
      file_type_list_arr.push(item.code)
    })
    if (!String(file_type_list_arr).includes(uploadType)) {
      proxy.$message.error({
        message: `文件格式【${uploadType}】非白名单文件类型格式，不支持上传`,
        showClose: true,
        duration: 3500,
      })
      return false
    }
  }
  //验证文件大小
  const maxFileSize = file.size / 1024 / 1024 < props.fileSize
  if (!maxFileSize) {
    proxy.$message.error(`上传文件大小不能超过${props.fileSize}Mb！`)
    return false
  }
}
//上传进度显示
const uploadVideoProcess = (event, file, fileList) => {
  state.videoFlag = true
  state.videoUploadPercent = file.percent
}
//上传成功
const handleVideoSuccess = (res, file) => {
  state.videoFlag = false
  state.videoUploadPercent = 0
  if (res.success) {
    const fileType = file.raw.type.split('/')[0]
    let obj = {}
    if (fileType === 'video') {
      obj = {
        url: file.url,
        type: 'video',
      }
    } else if (fileType === 'image') {
      obj = {
        url: file.url,
        type: 'img',
      }
    }
    state.fileList.push(obj)
    state.urlList.push(res.data[0])
  } else {
    proxy.$message.error('文件上传失败，请重新上传！')
  }
}
</script>

<style scoped>
.del-icon {
  width: 20px;
  height: 20px;
  line-height: 20px;
  border-bottom-left-radius: 15px;
  text-align: center;
  display: inline-block;
  background-color: #7f7f7f;
  color: #ffffff;
  background-size: 18px;
  background-repeat: no-repeat;
  background-position: 50%;
  position: relative;
  top: -136px;
  left: -23px;
}
.bgimg {
  border: 1px dashed #d9d9d9;
  border-radius: 4px;
  background-color: #ebeef5;
  background-image: url(../../assets/image/no-img.png);
  background-repeat: no-repeat;
  background-size: 40px 40px;
  background-position: 50% 50%;
}
.download-a {
  display: inline-block;
  color: #6dc1a9;
}
a:link {
  color: #606266;
} /* 未访问的链接 */
a:visited {
  color: #606266;
} /* 已访问的链接 */
a:hover {
  color: #6dc1a9;
} /* 鼠标在链接上 */
a:active {
  color: #6dc1a9;
} /* 点击激活链接*/
</style>
